//
//  JLMainViewController.m
//  LIangeNews
//
//  Created by sun on 16/1/10.
//  Copyright © 2016年 sun. All rights reserved.
//

#import "JLMainViewController.h"
#import "JLChannel.h"
#import "JLSocietyViewController.h"
#import "JLHeadlineController.h"
#import "JLHomeLabel.h"
#import "JLLeftDockMenu.h"
#import "UIView+Frame.h"
#import "JLLeftMenuButton.h"
#import "JLNavigationController.h"
typedef enum {
    JLLeftDockMenuTypeNews = 0, // 点击了 "新闻"
    JLLeftDockMenuTypeSubscription = 1, // 点击了 "订阅"
    JLLeftDockMenuTypePicture = 2, // 点击了 "图片"
    JLLeftDockMenuTypeVideo = 3, // 点击了 "视频"
    JLLeftDockMenuTypeReply = 4, // 点击了 "跟帖"
    JLLeftDockMenuTypeRadio = 5  // 点击了 "电台"
} JLLeftDockMenuType;
@interface JLMainViewController ()<UIScrollViewDelegate>
@property(nonatomic,strong)NSArray * channelList;
@property (weak, nonatomic) IBOutlet UIScrollView *titleScrollView;
@property (weak, nonatomic) IBOutlet UIScrollView *contentScrollView;
@property(nonatomic,weak)JLLeftDockMenu* leftDockMenu;
@end

@implementation JLMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupChinldVces];
    [self setupTitlelabel];
    [self setupDefalutController];
    JLHomeLabel * label = self.titleScrollView.subviews.firstObject;
    label.scale =1.0;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"sidebar_nav_news"] style:UIBarButtonItemStylePlain target:self action:@selector(leftItemClick)];
    [self setScrollViewProperties];
    [JLNoteCenter addObserver:self selector:@selector(leftMenuButtonSelected:) name:JLLeftMenuButtonDidSelectedNotification object:nil];
    
}
-(void)leftMenuButtonSelected:(NSNotification *)notification{
    [self leftDockSwitchVc:notification.object];
}
-(void)leftDockSwitchVc:(JLLeftMenuButton *)btn{
    switch (btn.tag) {
        case JLLeftDockMenuTypeNews:
            JLLog(@"点击了新闻");
            break;
        case JLLeftDockMenuTypeSubscription:
            JLLog(@"点击了订阅");
            break;
        case JLLeftDockMenuTypePicture:{
            JLLog(@"点击了图片");
            UIStoryboard * sb = [UIStoryboard storyboardWithName:@"Picture" bundle:nil];
            JLNavigationController * nav = [sb instantiateInitialViewController];
            CATransition * anim = [CATransition animation];
            anim.repeatDuration = 0.5;
            anim.type = @"cube";
            anim.removedOnCompletion = YES;
            anim.repeatCount =1;
            [self.view.layer addAnimation:anim forKey:nil];
            [self presentViewController:nav animated:YES completion:nil];
            
        }break;
        case JLLeftDockMenuTypeVideo:
            JLLog(@"点击了视频");
            break;
        case JLLeftDockMenuTypeReply:
            JLLog(@"点击了跟帖");
            break;
        case JLLeftDockMenuTypeRadio:
            JLLog(@"点击了电台");
            break;
        default:
            break;
    }
}
-(void)dealloc{
    [JLNoteCenter removeObserver:self];
}
-(void)leftItemClick{
    if (self.leftDockMenu) {
        if (self.contentScrollView.contentOffset.x < 0) {
            [self.contentScrollView setContentOffset:CGPointZero animated:YES];
        }else{
            [self.contentScrollView setContentOffset:CGPointMake(-200, 0) animated:YES];
        }
        
    }else{
        [self setupleftDockMenu];
        [self.contentScrollView setContentOffset:CGPointMake(-200, 0) animated:YES];
    }
}
-(void)setupleftDockMenu{
    JLLeftDockMenu *  leftDockMenu = [[JLLeftDockMenu alloc]init];
    leftDockMenu.size = CGSizeMake(150, 300);
    leftDockMenu.x = - 200;
    leftDockMenu.y = (self.contentScrollView.height - leftDockMenu.height) * 0.5;
    [self.contentScrollView addSubview:leftDockMenu];
    self.leftDockMenu  = leftDockMenu;

}
-(NSArray *)channelList{
    if (_channelList == nil) {
        NSString * path = [[NSBundle mainBundle]pathForResource:@"topic_news.json" ofType:nil];
        NSData * data = [NSData dataWithContentsOfFile:path];
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        NSArray * array = dict[dict.keyEnumerator.nextObject];
        NSMutableArray * arrayM = [NSMutableArray arrayWithCapacity:20];
        for (NSDictionary * dict in array) {
            JLChannel * channel = [JLChannel channelWithDict:dict];
            [arrayM addObject:channel];
        }
        _channelList = [arrayM sortedArrayUsingComparator:^NSComparisonResult(JLChannel * obj1, JLChannel * obj2) {
            return [obj1.tid compare:obj2.tid];
        }];
    }
    
    return _channelList;
}
-(void)setupDefalutController{
    JLHeadlineController * vc = (JLHeadlineController *)self.childViewControllers.firstObject;
    vc.view.frame = self.contentScrollView.bounds;
    [self.contentScrollView addSubview:vc.view];
    
}
-(void)setScrollViewProperties{
    self.titleScrollView.showsHorizontalScrollIndicator = NO;
    self.titleScrollView.showsVerticalScrollIndicator = NO;
    self.contentScrollView.showsHorizontalScrollIndicator = YES;
    self.contentScrollView.showsVerticalScrollIndicator = NO;
    self.contentScrollView.pagingEnabled = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    CGFloat contentX = [UIScreen mainScreen].bounds.size.width * self.childViewControllers.count;
    self.contentScrollView.contentSize = CGSizeMake(contentX, 0);
    self.contentScrollView.delegate = self;
    self.contentScrollView.userInteractionEnabled = YES;
//    self.contentScrollView.bounces = NO;
}
-(void)setupTitlelabel{
    
    NSUInteger count = self.childViewControllers.count;
    CGFloat width = 80;
    CGFloat height = 30;
    CGFloat y = 0;
    for (NSUInteger i = 0; i < count; i++) {
        JLHomeLabel * label = [[JLHomeLabel alloc]init];
        label.tag = i;
        label.text = self.childViewControllers[i].title;
        CGFloat x = width * i;
        label.frame = CGRectMake(x, y, width, height);
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(labelClick:)];
        [label addGestureRecognizer:tap];
        [self.titleScrollView addSubview:label];
    }
    
    CGFloat contentW = count * width;
    self.titleScrollView.contentSize = CGSizeMake(contentW, height);
    
}
-(void)labelClick:(UITapGestureRecognizer *)tap{
    JLHomeLabel * label = (JLHomeLabel *)tap.view;
    CGFloat offSet = label.tag * self.contentScrollView.frame.size
    .width;
    [self.contentScrollView setContentOffset:CGPointMake(offSet, 0) animated:YES];
    
}
-(void)setupChinldVces{
    UIStoryboard  * sb = [UIStoryboard storyboardWithName:@"Headline" bundle:nil];
    JLHeadlineController * headlineVc = [sb instantiateViewControllerWithIdentifier:@"Headline"];
    headlineVc.urlString = [self.channelList[0] tid];
    headlineVc.title = [self.channelList[0] tname];
    [self addChildViewController:headlineVc];
    
    UIStoryboard * sb1 = [UIStoryboard storyboardWithName:@"Society" bundle:nil];
    JLSocietyViewController * societyVc = [sb1 instantiateViewControllerWithIdentifier:@"Society"];
    JLChannel * channel1 = self.channelList[1];
    societyVc.title = channel1.tname;
    societyVc.urlString = channel1.tid;
    [self addChildViewController:societyVc];
    NSUInteger count = self.channelList.count - 2;
    
    for (int i = 2; i < count; i++) {
        UIViewController * vc = [[UIViewController alloc]init];
        vc.title = [self.channelList[i] tname];
        [self addChildViewController:vc];
    }
    
}


#pragma mark /******************scrollView的代理方法******************/
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.x < 0) return;
    NSUInteger index = scrollView.contentOffset.x / scrollView.width;
    JLHomeLabel * label = self.titleScrollView.subviews[index];
    CGFloat offSetX = label.centerX  - self.titleScrollView.width * 0.5;
    if (offSetX < 0) offSetX = 0;
    CGFloat maxOffSet = self.titleScrollView.contentSize.width - scrollView.width;
    if (offSetX > maxOffSet) offSetX = maxOffSet;
    [self.titleScrollView setContentOffset:CGPointMake(offSetX, 0) animated:YES];
    [self.titleScrollView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx != index) {
        JLHomeLabel * label = (JLHomeLabel *)self.titleScrollView.subviews[idx];
            label.scale = 0.0;
        }
    }];
    CGFloat x = index * scrollView.width;
    UIViewController * vc= self.childViewControllers[index];
    if (vc.view.superview) return;
    vc.view.frame = CGRectMake(x, 0, scrollView.width, scrollView.height);
    vc.view.backgroundColor = [UIColor colorWithRed:arc4random_uniform(256.0)/255.0 green:arc4random_uniform(256.0)/255.0 blue:arc4random_uniform(256.0)/255.0 alpha:1.0];
    [scrollView addSubview:vc.view];
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self scrollViewDidEndScrollingAnimation:scrollView];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.x < 0) return;
    CGFloat value = ABS(self.contentScrollView.contentOffset.x / self.contentScrollView.width);
    NSUInteger leftIndex  = (NSUInteger)value;
    NSUInteger rightIndex = leftIndex + 1;
    CGFloat rightScale = value - leftIndex;
    CGFloat leftScale = 1 - rightScale;
    JLHomeLabel * label = self.titleScrollView.subviews[leftIndex];
    label.scale = leftScale;
    if (rightIndex < self.titleScrollView.subviews.count) {
        JLHomeLabel * rigthLabel = self.titleScrollView.subviews[rightIndex];
        rigthLabel.scale = rightScale;
    }
    
}
@end
